<?php

namespace plugin\admin\app\controller;

use app\services\ConfigService;
use app\services\GoodsCategoryService;
use app\services\GoodsService;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\ConfigGroup;
use plugin\admin\app\model\Option;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Throwable;
use Webman\Config;

/**
 * 系统设置
 */
class ConfigController extends Base
{
    /**
     * 不需要验证权限的方法
     * @var string[]
     */
    protected $noNeedAuth = ['get'];

    /**
     * 账户设置
     * @return Response
     * @throws Throwable
     */
    public function index(Request $request): Response
    {
        $groupId = (array)$request->get('group_id');

        $query = ConfigGroup::orderBy('sort')->where('is_enable', 1);
        if ($groupId) {
            $query->whereIn('id', $groupId);
        }
        $groups = $query->get()->toArray();
        $scripts = '';

        foreach ($groups as $key=>$group) {
            $show = $key == 0 ? 'layui-show' : '';
            $startDiv = <<< EOF
<div class="layui-tab-item {$show}">
EOF;

            if ($group['type'] == ConfigGroup::TYPE_FORM) {
                $form = self::buildForm($group['id'], $scripts);
            } else if ($group['type'] == ConfigGroup::TYPE_LINK) {
                $form = '<iframe src="' . $group['link'] . '" frameborder="0" width="100%" height="100%" style="min-height: 600px;"></iframe>';
            }
            $endDiv = <<< EOF
</div>
EOF;

            $groups[$key]['form'] = $startDiv . $form . $endDiv;

        }

        return raw_view('config/index', [
            'groups' => $groups,
            'scripts' => $scripts
        ]);
    }

    public static function buildForm($groupId, &$scripts)
    {
        static $inputIndex = 0;
        static $uploadIndex = 0;
        $html = <<< EOF
<form class="layui-form" lay-filter="info{$groupId}">
EOF;
;

        $configs = \plugin\admin\app\model\Config::where('group_id', $groupId)->orderBy('sort')->get()->toArray();
        $innerScripts  = '';

        foreach ($configs as $config) {
            $value = $config['value'] ?? $config['input_default_value'];
            $hasQuestion = !empty($config['question']);

            if (!$config['is_enable']) {
                continue;
            }

            $questionHtml = '';
            if ($hasQuestion) {
                $question = urlencode($config['question']);
                $questionHtml = <<< EOF
<img src="/app/admin/question.png" id="{$config['key']}_question" onclick="showQuestion('$question', '{$config['key']}_question')" />
EOF;

            }

            switch ($config['input_type']) {
                default:
                case 'text':
                    $formItem = <<< EOF
        <div class="layui-form-item">
            <label class="layui-form-label">{$config['title']}{$questionHtml}</label>
            <div class="layui-input-block">
                <input type="text" name="{$config['key']}" value="{$value}"  lay-verify="required" placeholder="{$config['input_placeholder']}" autocomplete="off" class="layui-input">
            </div>
        </div>
EOF;
                    break;
                case 'radio':
                    $formItem = <<< EOF
        <div class="layui-form-item">
            <label class="layui-form-label">{$config['title']}{$questionHtml}</label>
            <div class="layui-input-block">
EOF;
                    $options = json_decode($config['input_select_options'], true);
print_r($options);
                    foreach ($options as $option) {
                        $checked = $option['value'] == $value ? 'checked' : '';
                        $formItem .= <<< EOF
    <input type="radio" name="{$config['key']}" value="{$option['value']}" title="{$option['title']}" {$checked}>
EOF;
                    }

                    $formItem .= <<< EOF
    </div>
</div>
EOF;
                    break;
                case 'checkbox':
                    $formItem = <<< EOF
        <div class="layui-form-item">
            <label class="layui-form-label">{$config['title']}{$questionHtml}</label>
            <div class="layui-input-block">
EOF;
                    $options = json_decode($config['input_select_options'], true);
                    $values = explode(',', $value);

                    foreach ($options as $option) {
                        $checked = in_array($option['value'], $values) ? 'checked' : '';
                        $formItem .= <<< EOF
    <input type="checkbox" name="{$config['key']}[]" value="{$option['value']}" title="{$option['title']}" {$checked}>
EOF;
                    }

                    $formItem .= <<< EOF
    </div>
</div>
EOF;

                    $innerScripts .= <<< EOF
if (typeof data.field['{$config['key']}[0]'] == 'undefined') {
data.field['{$config['key']}'] = '';
}
EOF;
                    break;
                case 'textarea':
                    $formItem = <<< EOF
        <div class="layui-form-item">
            <label class="layui-form-label">{$config['title']}{$questionHtml}</label>
            <div class="layui-input-block">
                <textarea name="{$config['key']}" class="layui-textarea" placeholder="{$config['input_placeholder']}" id="" cols="10" rows="5">{$value}</textarea>
            </div>
        </div>
EOF;
                    break;
                case 'file':
                    $formItem = <<< EOF
        <div class="layui-form-item">
            <label class="layui-form-label">{$config['title']}{$questionHtml}</label>
            <div class="layui-input-block">
                <span>{$value}</span>
                 <input type="text" style="display:none" name="{$config['key']}" value="{$value}" />
                <button type="button" class="pear-btn pear-btn-primary pear-btn-sm" id="image{$uploadIndex}" permission="app.admin.upload.avatar">
                    <i class="layui-icon layui-icon-upload"></i>上传
                </button>
            </div>
        </div>
EOF;
                    break;
                case 'image':
                    $formItem = <<< EOF
        <div class="layui-form-item">
            <label class="layui-form-label">{$config['title']}{$questionHtml}</label>
            <div class="layui-input-block">
                <img width="100" src=""/>
                <input type="text" style="display:none" name="{$config['key']}" value="{$value}" />
                <button type="button" class="pear-btn pear-btn-primary pear-btn-sm" id="image{$uploadIndex}" permission="app.admin.upload.avatar">
                    <i class="layui-icon layui-icon-upload"></i>上传
                </button>
            </div>
        </div>
EOF;
                    break;
                case 'switch':
                    $options = json_decode($config['input_select_options'], true);
                    $text = join('|', array_column($options, 'title'));
                    $checked = $value == 1 ? 'checked' : '';
                    $formItem = <<< EOF
<div class="layui-form-item">
    <label class="layui-form-label">{$config['title']}{$questionHtml}</label>
    <div class="layui-input-block">
        <input type="checkbox" name="{$config['key']}" id="{$config['key']}" lay-skin="switch" lay-text="{$text}" {$checked} />
    </div>
</div>
EOF;
                    $innerScripts .= <<< EOF
data.field['{$config['key']}'] = layui.$('#{$config['key']}').is(':checked') ? 1 : 0;
EOF;

                    break;
            }

            if ($config['input_type'] == 'image' || $config['input_type'] == 'file') {
                if ($config['input_type'] == 'image') {
                    $option = <<< EOF
acceptMime: "image/gif,image/jpeg,image/jpg,image/png",
EOF;

                    $doneCallback = <<< EOF
this.item.prev().val(res.data.url).prev().attr("src", res.data.url);
EOF;
                } else {
                    $option = <<< EOF
accept: "file",
field: "__file__",
EOF;

                    $doneCallback = <<< EOF
this.item.prev().val(res.data.url).prev().html(layui.util.escape(res.data.url));
EOF;
                }

                $scripts .= <<< EOF
                let input{$inputIndex} = $("#image{$uploadIndex}").prev();
                input{$inputIndex}.prev().attr("src", input{$inputIndex}.val());
                layui.upload.render({
                    elem: "#image{$uploadIndex}",
                    url: "/app/admin/upload/{$config['input_type']}",
                    {$option}
                    done: function (res) {
                        if (res.code) {
                            return layui.popup.failure(res.msg);
                        }
                        {$doneCallback}
                    }
                });
EOF;
                $inputIndex++;
                $uploadIndex++;
            }



            $html .= $formItem;
        }

        $scripts .= <<< EOF
form.on("submit(saveInfo{$groupId})", function(data){
{$innerScripts}
            $.ajax({
                url: "/app/admin/config/update",
                dataType: "json",
                type: "POST",
                data: data.field,
                success: function (res) {
                    if (res.code) {
                        return layui.popup.failure(res.msg);
                    }
                    return layui.popup.success("操作成功");
                }
            });
            return false;
        });
EOF;

        $html .= <<< EOF
<div class="layui-form-item">
        <div class="layui-input-block">
        <input type="hidden" name="group_id" value="{$groupId}" />
            <button type="submit" class="pear-btn pear-btn-primary pear-btn-md" lay-submit="" lay-filter="saveInfo{$groupId}">
                提交
            </button>
        </div>
    </div>
</form>
EOF;

        return $html;
    }

    /**
     * 获取配置
     * @return Response
     */
    public function get(): Response
    {
        return json($this->getByDefault());
    }

    /**
     * 基于配置文件获取默认权限
     * @return mixed
     */
    protected function getByDefault()
    {
        $name = 'system_config';
        $config = Option::where('name', $name)->value('value');
        if (empty($config)) {
            $config = file_get_contents(base_path('plugin/admin/public/config/pear.config.json'));
            if ($config) {
                $option = new Option();
                $option->name = $name;
                $option->value = $config;
                $option->save();
            }
        }

        $siteName = ConfigService::get('site_name');
        $config = json_decode($config, true);
        $config['logo']['title'] = $siteName;
        $logo = ConfigService::get('site_logo');
        $config['logo']['image'] = $logo;

        return $config;
    }

    /**
     * 更改
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        $data = $request->post();

        foreach ($data as $key=>$item) {
            if (is_array($item)) {
                $item = join(',', $item);
            }
            \plugin\admin\app\model\Config::where('key', $key)->update(['value' => $item]);
        }

        return $this->json(0);
    }

    /**
     * 颜色检查
     * @param string $color
     * @return string
     * @throws BusinessException
     */
    protected function filterColor(string $color): string
    {
        if (!preg_match('/\#[a-zA-Z]6/', $color)) {
            throw new BusinessException('参数错误');
        }
        return $color;
    }

    public function getList()
    {
        $data = [
            [
                'name' => '特享专区',
                'value' => '/pages/v2/store/specialGoods?type=texiang'
            ],
            [
                'name' => '爆款推荐',
                'value' => '/pages/v2/store/specialGoods?type=baokuan'
            ],
            [
                'name' => '孝友好评',
                'value' => '/pages/goods/list?type=good&title=孝友好评'
            ],
            [
                'name' => '国潮好货',
                'value' => '/pages/goods/list?type=chic&title=国潮好货'
            ],
        ];

        $list = GoodsCategoryService::list();

        foreach ($list as $value) {
            $data[] = [
                'name' => $value['mobile_show_name'],
                'value' => sprintf("/pages/goods/list?id=%s&title=%s", $value['id'], $value['mobile_show_name'])
            ];
        }

        return $this->json(0, '成功', $data);
    }

}
